package com.jlsoft.config.web.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.jlsoft.config.SimpleResponse;
import com.jlsoft.config.web.service.AppService;
import com.jlsoft.config.web.vo.PersonUser;
import com.jlsoft.entity.SysData;
import com.jlsoft.entity.User;
import com.jlsoft.service.ISysDataService;
import com.jlsoft.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.util.Calendar;
import java.util.List;

@Service
@Slf4j
public class AppServiceImpl implements AppService {

    @Override
    public SimpleResponse validateUpdateUser(PersonUser personUser) {

        if (!StringUtils.isEmpty(personUser.getNewUserPassword()) && !StringUtils.isEmpty(personUser.getOriginalPassword())) {
            User user = userService.selectById(personUser.getId());

            if (!passwordEncoder.matches(personUser.getOriginalPassword(), user.getUserPassword())) {
                return new SimpleResponse(10, "原始密码错误", false);
            }
        }
        return new SimpleResponse(0, "", true);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SimpleResponse updateUser(PersonUser personUser) {

        User user = new User();
        BeanUtils.copyProperties(personUser, user);
        if (!StringUtils.isEmpty(personUser.getNewUserPassword()) && !StringUtils.isEmpty(personUser.getOriginalPassword())) {
            user.setUserPassword(passwordEncoder.encode(personUser.getNewUserPassword()));
        }

        return userService.updateById(user) ?
                new SimpleResponse(0, "更新成功", true) : new SimpleResponse(10, "更新失败", false);
    }

    @Override
    public void testForBaiDuApi() {
        List<SysData> sysDataList = dataService.selectList(new EntityWrapper<SysData>()
                .eq("sid", "867378032095632")
                .eq("location_State", "1")
                .orderBy("location_Time")
        );
        log.debug("查询的结果记录数:{}", sysDataList.size());
        sysDataList.stream().forEach(sysData -> {
            //https://blog.csdn.net/yiifaa/article/details/77939282
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(sysData.getLocationTime());
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
            params.add("ak", ak);
            params.add("service_id", "164420");
            params.add("entity_name", "myphone");
            params.add("latitude", sysData.getLat());
            params.add("longitude", sysData.getLng());
            params.add("loc_time", calendar.getTimeInMillis() / 1000 + "");
            params.add("coord_type_input", "bd09ll");
            params.add("speed", sysData.getSpeed());
            HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(params, headers);
            ResponseEntity<String> response = restTemplate.exchange(addPointApi, HttpMethod.POST, requestEntity, String.class);
            log.debug("输出结果:{}", response.getBody());
        });


    }

    @Autowired
    private IUserService userService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private ISysDataService dataService;

    @Autowired
    private RestTemplate restTemplate;

    private static final String ak = "O9lHpHVEwWxC9vd8cG7DI7gUa2Egxofp";

    private static final String addPointApi = "http://yingyan.baidu.com/api/v3/track/addpoint";
}
